package qj.tool.jna;

import java.util.LinkedList;
import java.util.List;

import qj.util.ThreadUtil;
import qj.util.funct.F1;
import qj.util.funct.F2;
import qj.util.funct.P0;

public class KeyCombiMapper {

	public static Mapper mapper(int modKey) {
		final boolean[] waitingCommand = {false};
		
		final List<Task> list = new LinkedList<Task>();
		
		KeyboardHandler.mapAll(new F2<Integer,Boolean, Boolean>() {public Boolean e(Integer key, Boolean pressed) {
			if (waitingCommand[0]) {
				
				if (!pressed) {
					AA:
					for (Task task : list) {
						int[] btns = task.btns;
						if (key == btns[btns.length - 1]) {
							for (int i = 0; i < btns.length - 1; i++) {
								if (!KeyboardHandler.isPressed(btns[i])) {
									continue AA;
								}
							}

							waitingCommand[0] = false;
							ThreadUtil.run(task.action);
							
							return false;
						}
					}
					
				}
				
				return false;
			}
			return true;
		}});
		KeyboardHandler.map(modKey, new F1<Boolean, Boolean>() {public Boolean e(Boolean obj) {
			waitingCommand[0] = obj;
			return false;
		}});
		return new Mapper(){
			public void map(int btn, final P0 p0) {
				map(new int[] {btn}, p0);
			}
			
			public void map(final int[] btns, final P0 p0) {
				Task task = new Task();
				task.btns = btns;
				task.action = p0;
				list.add(task);
			}
		};
	}

	public static interface Mapper {
		void map(int[] btn, P0 p0);
		void map(int btn, P0 p0);
	}

	public static class Task {
		public int[] btns;
		public P0 action;
	}

}
